package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.Tools;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.AccountEntity;
import io.renren.modules.sys.entity.DepotEntity;
import io.renren.modules.sys.entity.DepotheadEntity;
import io.renren.modules.sys.entity.SupplierEntity;
import io.renren.modules.sys.service.AccountService;
import io.renren.modules.sys.service.DepotheadService;
import io.renren.modules.sys.service.SupplierService;
import io.renren.modules.sys.shiro.ShiroUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;


/**
 * 单据主表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-22 14:29:36
 */
@RestController
@RequestMapping("sys/depothead")
public class DepotheadController {
    @Autowired
    private DepotheadService depotheadService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private SupplierService supplierService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:depothead:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = depotheadService.queryPage(params);

        return R.ok().put("page", page);
    }


    @RequestMapping("/findBy")
    public R findBy(@RequestParam Map<String, Object> params){
//        limit page
        String pageSize = "15";
        String pageNo = "1";
        Object pageSizeObj = params.get("pageSize");
        Object pageNoObj = params.get("pageNo");
        if(pageSizeObj!=null){
            pageSize=pageSizeObj.toString();
        }
        if(pageNoObj!=null){
            pageNo=pageNoObj.toString();
        }
        params.put("limit",pageSize);
        params.put("page",pageNo);
        List<DepotheadEntity> list = depotheadService.findBy(params);
        JSONArray dataArray = new JSONArray();
        for(DepotheadEntity depothead : list){

            String accountIdList = depothead.getAccountidlist();
            String accountMoneyList = depothead.getAccountmoneylist();
            if(accountIdList!=null){
                accountIdList = accountIdList.replace("[", "").replace("]", "").replace("\"", "");
                String[] aList = accountIdList.split(",");
                depothead.setAccountidattr(aList);
            }
            if(accountMoneyList!=null){
                accountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replace("\"", "");
                String[] amList = accountMoneyList.split(",");

                depothead.setAccountmoneyattr(amList);
            }

            if(depothead.getOrganid()!=null){
                SupplierEntity supplier = supplierService.selectById(depothead.getOrganid());
                depothead.setOrganName(supplier.getSupplier());
            }


            AccountEntity accountEntity = accountService.selectById(depothead.getAccountid());

            if(accountEntity!=null){

                depothead.setAccountname(accountEntity.getName());
            }
            if(depothead.getId()!=null){
                String materialsList = findMaterialsListByHeaderId(depothead.getId());
                depothead.setMaterialsList(materialsList);
            }
            JSONObject json = getJsonString(depothead);
            dataArray.add(json);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total",list.size());
        jsonObject.put("rows",dataArray);
        return R.ok().put("data",jsonObject);
    }


    @RequestMapping("/findGiftReport")
    public R findGiftReport(@RequestParam Map<String, Object> params) {
//        limit page
        List<DepotheadEntity> dataList_in = depotheadService.selectList(new EntityWrapper<DepotheadEntity>().orderBy("Id"));
        List<Long> headIds = new ArrayList<>();
        for(DepotheadEntity entity :dataList_in){
            headIds.add(entity.getId());
        }

        return R.ok().put("HeadIds",headIds);
    }

    @RequestMapping("/findTotalPay")
    public R findTotalPay(@RequestParam Map<String, Object> params) {

        String supType = Tools.dealNullStr(params.get("supType"));
        String getS = Tools.dealNullStr(params.get("supplierId"));

        int i=0;
        if ("customer".equals(supType)) { //客户
            i = 1;
        } else if ("vendor".equals(supType)) { //供应商
            i = -1;
        }

        Double sum = 0.0;
        //进销部分
        sum = sum - (allMoney(getS, "入库", "采购", "合计") - allMoney(getS, "入库", "采购", "实际")) * i;
        sum = sum - (allMoney(getS, "入库", "销售退货", "合计") - allMoney(getS, "入库", "销售退货", "实际")) * i;
        sum = sum + (allMoney(getS, "出库", "销售", "合计") - allMoney(getS, "出库", "销售", "实际")) * i;
        sum = sum + (allMoney(getS, "出库", "采购退货", "合计") - allMoney(getS, "出库", "采购退货", "实际")) * i;


        return R.ok().put("getAllMoney",sum);
    }

    public Double allMoney(String getS, String type, String subType, String mode) {
        Double sumNumber = 0.00;
        try {
            sumNumber= depotheadService.findAllMoney(getS, type,subType,mode);
            if (sumNumber==null) {
                sumNumber = 0.00;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sumNumber;
    }

    @RequestMapping("/findByMonth")

    public List<Long> findByMonth(@RequestParam Map<String, Object> params) {
//        limit page
        String pageSize = "15";
        String pageNo = "1";
        Object pageSizeObj = params.get("pageSize");
        Object pageNoObj = params.get("pageNo");
        if (pageSizeObj != null) {
            pageSize = pageSizeObj.toString();
        }
        if (pageNoObj != null) {
            pageNo = pageNoObj.toString();
        }
        params.put("limit", pageSize);
        params.put("page", pageNo);

        Page<DepotheadEntity> page = depotheadService.selectPage(
                new Query<DepotheadEntity>(params).getPage(),
                new EntityWrapper<DepotheadEntity>()
                        .eq("OperTime", params.get("MonthTime").toString())
                        .or()
                        .lt("OperTime", params.get("MonthTime").toString())
                        .orderBy("Id")
        );

        PageUtils pageUtils = new PageUtils(page);
        List<DepotheadEntity> list = (List<DepotheadEntity>) pageUtils.getList();
        List<Long> longs = new ArrayList<>();
        for(DepotheadEntity entity:list){
            longs.add(entity.getId());
        }
        return longs;
    }
    @RequestMapping("/getDetailByNumber")
    public DepotheadEntity getDetailByNumber(@RequestParam Map<String, Object> params){
        DepotheadEntity depotheadEntity = depotheadService.selectOne(new EntityWrapper<DepotheadEntity>().eq("number",params.get("Number").toString()));
        String accountIdList = depotheadEntity.getAccountidlist();
        String accountMoneyList = depotheadEntity.getAccountmoneylist();
        if(accountIdList!=null){
            accountIdList = accountIdList.replace("[", "").replace("]", "").replace("\"", "");
            String[] aList = accountIdList.split(",");
            depotheadEntity.setAccountidattr(aList);
        }
        if(accountMoneyList!=null){
            accountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replace("\"", "");
            String[] amList = accountMoneyList.split(",");

            depotheadEntity.setAccountmoneyattr(amList);
        }


        AccountEntity accountEntity = accountService.selectById(depotheadEntity.getAccountid());

        if(accountEntity!=null){

            depotheadEntity.setAccountname(accountEntity.getName());
        }
        return depotheadEntity;
    }
	
	/**
     *
     * @param params
     * @return
     */
    @RequestMapping("/findStatementAccount")
    public R findStatementAccount(@RequestParam Map<String, Object> params){
        int j = 1;
        if (params.get("supType").equals("客户")) { //客户
            j = 1;
        } else if (params.get("supType").equals("供应商")) { //供应商
            j = -1;
        }
        List dataList = depotheadService.findStatementAccount(params);
        JSONObject outer = new JSONObject();
        outer.put("total", dataList.size());
        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if (dataList != null) {
            for (Integer i = 0; i < dataList.size(); i++) {
                JSONObject item = new JSONObject();
                Map dl = (Map) dataList.get(i); //获取对象
//                Object[] arr = (Object[]) dl; //转为数组
                item.put("number", dl.get("number")); //单据编号
                item.put("type", dl.get("newtype")); //类型
                String type = dl.get("newtype").toString();
                Double p1 = 0.0;
                Double p2 = 0.0;
                if (dl.get("discountlastmoney") != null) {
                    p1 = Double.parseDouble(dl.get("discountlastmoney").toString());
                }
                if (dl.get("changeamount") != null) {
                    p2 = Double.parseDouble(dl.get("changeamount").toString());
                }
                Double allPrice = 0.0;
                if (p1 < 0) {
                    p1 = -p1;
                }
                if (p2 < 0) {
                    p2 = -p2;
                }
                if (type.equals("采购入库")) {
                    allPrice = -(p1 - p2);
                } else if (type.equals("销售退货入库")) {
                    allPrice = -(p1 - p2);
                } else if (type.equals("销售出库")) {
                    allPrice = p1 - p2;
                } else if (type.equals("采购退货出库")) {
                    allPrice = p1 - p2;
                } else if (type.equals("付款")) {
                    allPrice = p1 + p2;
                } else if (type.equals("收款")) {
                    allPrice = -(p1 + p2);
                } else if (type.equals("收入")) {
                    allPrice = p1 - p2;
                } else if (type.equals("支出")) {
                    allPrice = -(p1 - p2);
                }
                item.put("discountLastMoney", p1); //金额
                item.put("changeAmount", p2); //金额
                item.put("allPrice", String.format("%.2f", allPrice * j)); //计算后的金额
                item.put("supplierName", dl.get("supplier")); //供应商
                item.put("operTime", dl.get("otime")); //入库出库日期
                dataArray.add(item);
            }
        }
        outer.put("rows", dataArray);
        return R.ok().put("depothead", outer);
    }

    /**
     * 入库出库统计接口
     *
     * pageNo: 1
     * pageSize: 10
     * OrganId:
     * ProjectId:
     * DepotIds: 1,4,2,3,5
     * BeginTime: 2018-11-01 00:00:00
     * EndTime: 2018-11-26 15:30:13
     * Type: 出库
     *
     * {"total":1,"rows":[{"MaterialId":500,"mName":"纯棉线","Model":"AAA666","categoryName":"根目录","numSum":1,"priceSum":1.3}]}
     * @return
     */
    @RequestMapping("findInOutMaterialCount")
    public R findInOutMaterialCount(@RequestParam Map<String, Object> params){
        List dataList = depotheadService.findInOutMaterialCount(params);

        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if (dataList != null) {
            for (Integer i = 0; i < dataList.size(); i++) {
                JSONObject item = new JSONObject();
                Map dl = (Map) dataList.get(i); //获取对象
                item.put("MaterialId", dl.get("materialId")); //商品Id
                item.put("mName", dl.get("mName")); //商品名称
                item.put("Model", dl.get("model")); //商品型号
                item.put("categoryName", dl.get("categoryName")); //商品类型
                item.put("numSum", dl.get("numSum")); //数量
                item.put("priceSum", dl.get("priceSum")); //金额
                dataArray.add(item);
            }
        }
        return R.ok().put("total", dataList.size()).put("rows", dataArray);
    }

    /**
     * 入库出库明细接口
     * @param params
     * @return
     */
    @RequestMapping("/findInDetail")
    public R findInDetail(@RequestParam Map<String, Object> params){
        List dataList = depotheadService.findInDetail(params);

        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if (dataList != null) {
            for (Integer i = 0; i < dataList.size(); i++) {
                JSONObject item = new JSONObject();
                Map dl = (Map) dataList.get(i); //获取对象
                item.put("number", dl.get("number")); //单据编号
                item.put("materialName", dl.get("materialName")); //商品名称
                item.put("materialModel", dl.get("materialModel")); //商品型号
                item.put("unitPrice", dl.get("unitPrice")); //单价
                item.put("operNumber", dl.get("operNumber")); //入库出库数量
                item.put("allPrice", dl.get("allPrice")); //金额
                item.put("supplierName", dl.get("supplierName")); //供应商
                item.put("depotName", dl.get("depotName")); //仓库
                item.put("operTime", dl.get("operTime")); //入库出库日期
                item.put("type", dl.get("type")); //入库出库日期
                dataArray.add(item);
            }
        }
        return R.ok().put("total", dataList.size()).put("rows", dataList);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:depothead:info")
    public R info(@PathVariable("id") Long id){
        DepotheadEntity depothead = depotheadService.selectById(id);

        return R.ok().put("depothead", depothead);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:depothead:save")
    public R save(@RequestBody DepotheadEntity depothead){
        depotheadService.insert(depothead);

        return R.ok();
    }

    /**
     * 修改
     */
//    @RequestMapping("/update")
//    @RequiresPermissions("sys:depothead:update")
//    public R update(@RequestBody DepotheadEntity depothead){
//        ValidatorUtils.validateEntity(depothead);
//        depotheadService.updateAllColumnById(depothead);//全部更新
//
//        return R.ok();
//    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:depothead:delete")
    public R delete(@RequestBody Long[] ids){
        depotheadService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }


    @RequestMapping("/getHeaderIdByMaterial")
    public R getHeaderIdByMaterial(@RequestParam Map<String, Object> params) {

        String depotIds = (String)params.get("DepotIds");

        String[] depotId = depotIds.split("\\,");
        params.put("DepotIds",depotId);
        List<String> dataList = depotheadService.getHeaderIdByMaterial(params);

        JSONObject outer = new JSONObject();
        String allReturn = "";
        if (dataList != null) {
            for (Integer i = 0; i < dataList.size(); i++) {
                String dl =  dataList.get(i); //获取对像
                allReturn = allReturn + dl + ",";
            }
        }
        allReturn = allReturn.substring(0, allReturn.length() - 1);
        if (allReturn.equals("null")) {
            allReturn = "";
        }
        return R.ok().put("ret", allReturn);



    }

    public String findMaterialsListByHeaderId(Long id){
        String allReturn = "";
        Map params = new HashMap();
        params.put("id",id);
        try {
            allReturn = depotheadService.findMaterialsListByHeaderId(params);
            allReturn = allReturn.substring(1, allReturn.length() - 1);
            if (allReturn.equals("null")) {
                allReturn = "";
            }
        } catch (Exception e) {
            R.ok().error(e.getMessage());
        }
        return allReturn;
    }

    public JSONObject getJsonString(DepotheadEntity depotHead){
        JSONObject item = new JSONObject();
        item.put("Id", depotHead.getId());
        item.put("ProjectId", depotHead.getProjectid()== null ? "" : depotHead.getProjectid());
        item.put("ProjectName", depotHead.getProjectid() == null ? "" : depotHead.getProjectid());
        item.put("Number", depotHead.getNumber());
        item.put("OperPersonName", depotHead.getOperpersonname());
        item.put("CreateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(depotHead.getCreatetime()));
        item.put("OperTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(depotHead.getOpertime()));
        item.put("OrganId", depotHead.getOrganid() == null ? "" : depotHead.getOrganid());
        item.put("OrganName", depotHead.getOrganName() == null ? "" : depotHead.getOrganName());
        item.put("HandsPersonId", depotHead.getHandspersonid() == null ? "" : depotHead.getHandspersonid());
        item.put("Salesman", depotHead.getSalesman().toString());
        item.put("HandsPersonName", depotHead.getHandspersonid() == null ? "" : depotHead.getHandspersonid());
        item.put("AccountId", depotHead.getAccountid() == null ? "" : depotHead.getAccountid());
        item.put("AccountName", depotHead.getAccountname()== null ? "" : depotHead.getAccountname());
        item.put("ChangeAmount", depotHead.getChangeamount() == null ? "" : Math.abs(depotHead.getChangeamount()));
        item.put("AccountIdList", depotHead.getAccountidlist());
        item.put("AccountMoneyList", depotHead.getAccountmoneylist());
        item.put("Discount", depotHead.getDiscount());
        item.put("DiscountMoney", depotHead.getDiscountmoney());
        item.put("DiscountLastMoney", depotHead.getDiscountlastmoney());
        item.put("OtherMoney", depotHead.getOthermoney());
        item.put("OtherMoneyList", depotHead.getOthermoneylist()); //id列表
        item.put("OtherMoneyItem", depotHead.getOthermoneyitem()); //money列表
        item.put("AccountDay", depotHead.getAccountday()); //结算天数
        item.put("AllocationProjectId", depotHead.getAllocationprojectid() == null ? "" : depotHead.getAllocationprojectid());
        item.put("AllocationProjectName", depotHead.getAllocationprojectid() == null ? "" : depotHead.getAllocationprojectid());
        item.put("TotalPrice", depotHead.getTotalprice() == null ? "" : Math.abs(depotHead.getTotalprice()));
        item.put("payType", depotHead.getPaytype() == null ? "" : depotHead.getPaytype());
        item.put("Status", depotHead.getStatus());
        item.put("Remark", depotHead.getRemark());
        item.put("MaterialsList", findMaterialsListByHeaderId(depotHead.getId()));
        item.put("op", 1);
        return  item;
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:depothead:update")
    public R update(@RequestParam Map<String, Object> params){
        DepotheadEntity depotHead = depotheadService.selectById(params.get("DepotHeadID").toString());
        depotHead.setType((String) params.get("Type"));
        depotHead.setSubtype((String) params.get("SubType"));
        if ((String) params.get("ProjectId") != null) {
            depotHead.setProjectid(Long.valueOf((String) params.get("ProjectId")));
        }
        depotHead.setNumber((String) params.get("Number"));
        depotHead.setOperpersonname( ShiroUtils.getUserEntity().getUsername());
        try {
            depotHead.setOpertime(new Timestamp(Tools.parse(params.get("OperTime").toString(), "yyyy-MM-dd HH:mm:ss").getTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (params.get("OrganId") != null) {
            depotHead.setOrganid(Long.valueOf((String)params.get("OrganId")));
        }
        if (params.get("HandsPersonId") != null) {
            depotHead.setHandspersonid(Long.valueOf((String)params.get("HandsPersonId")));
        }
        depotHead.setSalesman((String)params.get("Salesman"));
        if ((String)params.get("AccountId") != null) {
            depotHead.setAccountid(Long.valueOf((String)params.get("AccountId")));
        } else {
            depotHead.setAccountid(null);
        }
        depotHead.setChangeamount(Double.valueOf((String)params.get("ChangeAmount")));
        depotHead.setAccountidlist((String)params.get("AccountIdList"));
        depotHead.setAccountmoneylist((String)params.get("AccountMoneyList"));
        depotHead.setDiscount(Double.valueOf((String)params.get("Discount")));
        depotHead.setDiscountmoney(Double.valueOf((String)params.get("DiscountMoney")));
        depotHead.setDiscountlastmoney(Double.valueOf((String)params.get("DiscountLastMoney")));
        depotHead.setOthermoney(Double.valueOf((String)params.get("OtherMoney")));
        depotHead.setOthermoneylist((String)params.get("OtherMoneyList"));
        depotHead.setOthermoneyitem((String)params.get("OtherMoneyItem"));
        depotHead.setAccountday((int)params.get("AccountDay"));
        if ((String)params.get("AllocationProjectId") != null) {
            depotHead.setAllocationprojectid(Long.valueOf((String)params.get("AllocationProjectId")));
        }
        depotHead.setTotalprice(Double.valueOf((String)params.get("TotalPrice")));
        depotHead.setPaytype((String)params.get("PayType"));
        depotHead.setStatus(false);
        depotHead.setRemark((String)params.get("Remark"));


        ValidatorUtils.validateEntity(depotHead);
        depotheadService.updateAllColumnById(depotHead);//全部更新

        return R.ok();
    }


}
